package com.shaoshaohuo.app.ui.ec;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.liam.imageload.LoadUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.AddedServiceListAdapter;
import com.shaoshaohuo.app.adapter.CarTypeSecondListAdapter;
import com.shaoshaohuo.app.constant.CarOption;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.FileType;
import com.shaoshaohuo.app.db.DaoUtils;
import com.shaoshaohuo.app.entity.AddedService;
import com.shaoshaohuo.app.entity.Baoxian;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.CarTypeFirst;
import com.shaoshaohuo.app.entity.CarTypeSecond;
import com.shaoshaohuo.app.entity.PoiEntity;
import com.shaoshaohuo.app.entity.SupplyOrder;
import com.shaoshaohuo.app.entity.UploadImageEntity;
import com.shaoshaohuo.app.entity.post.SendGoodsEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.Logger;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.OrderManagerActivity;
import com.shaoshaohuo.app.ui.shipper.MyOrderShipperActivity;
import com.shaoshaohuo.app.utils.AudioPlayManager;
import com.shaoshaohuo.app.utils.AudioPlayManager.PlayingListener;
import com.shaoshaohuo.app.utils.AudioPlayManager.RecordingListener;
import com.shaoshaohuo.app.utils.CameraUtil;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.FileHelper;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.PoiEntityUtils;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.view.DatepickerPopwindow;
import com.shaoshaohuo.app.view.DatepickerPopwindow.OnSelectDateListener;
import com.shaoshaohuo.app.view.MeasureGridView;
import com.shaoshaohuo.app.view.TimepickerPopwindow;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.entity.Area;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;

import org.hybridsquad.android.library.CropHandler;
import org.hybridsquad.android.library.CropHelper;
import org.hybridsquad.android.library.CropParams;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SendGoodsActivity
 * @Decription
 */
public class SendGoodsEcActivity extends BaseActivity implements OnClickListener, CropHandler {

	private static final int SELECT_START_POI = 100;
	private static final int SELECT_END_POI = 101;

	private static final int UPLOAD_PHOTO1 = 100;
	private static final int UPLOAD_PHOTO2 = 101;
	private static final int UPLOAD_PHOTO3 = 102;
	private static final int UPLOAD_AUDIO = 103;

	private TopbarView mTopbarView;

	private ScrollView mContentSv;

	private View mStartAddressLayout;
	private View mEndAddressLayout;
	private TextView mStartAddressText;
	private TextView mEndAddressText;
	private EditText mStartAddressEdit;
	private EditText mEndAddressEdit;
	private View mSendTimeLayout;
	private TextView mSendTimeText;
	private View mWantTimeLayout;
	private TextView mWantTimeText;
	private View mCargoTypeLayou;
	private TextView mCargoTypeText;
	private View mCargoweightLayout;
	private EditText mCargoweightEdit;
	private View mCargoTijiLayout;
	private EditText mCargoTijiText;
	private View mCargoweight1Layout;
	private EditText mCargoweight1Edit;
	private View mCargoTiji1Layout;
	private EditText mCargoTiji1Text;
	private View mCargoLongLayout;
	private EditText mCargoLongEdit;

	private View mPhoto1Layout;
	private View mPhoto2Layout;
	private View mPhoto3Layout;
	private ImageView mPhoto1Image;
	private ImageView mPhoto2Image;
	private ImageView mPhoto3Image;
	private EditText mContactPhoneEdit;
	private View mCarYaoqiuLayout;
	private TextView mCarYaoqiuText;

	private MeasureGridView mAddedServiceGv;
	private TextView mBxDeleteButton;
	private TextView mBxAddButton;
	private TextView mBxCountText;
	private EditText mMarkEdit;
	private TextView mBxHintText;
	private TextView mBxHintCountText;

	private View mYunfeiLayout;
	private EditText mYunfeiEdit;

	private View mAudioRecordLayout;
	private TextView mAudioRecordText;
	private View mAudioPlayLayout;
	private Button mReleaseButton;

	private View mCargoNameLayou; //1.8
	private EditText mCargoNameText;
	private View mPayLayout;
	private TextView mPayText;

	private View mCarTypeLayout;
	private View mCarLongLayout;
	private View mCarWeightLayout;
	private TextView mCarTypeText;
	private TextView mCarlongText;
	private TextView mCarWeightText;

	private List<AddedService> mSelectedServiceList = new ArrayList<>();

	private AudioPlayManager manager;
	private boolean isRecording = false;
	private String recordPath;

	private AlertDialog recordDialog;

	private String caruserid;
	// 是否一车驱动
	private boolean isCar = false;

	private PoiEntity startPoi;
	private PoiEntity endPoi;

	// protected int sendTimeYear;
	// protected int sendTimeMonth;
	// protected int sendTimeDay;

	private String sendDate = "";
	private String wantDate = "";
	// protected int sendTimeHour;
	// protected int sendTimeMinute;

	// protected int wantTimeYear;
	// protected int wantTimeMonth;
	// protected int wantTimeDay;
	protected int shipptype = -1;

	private String mPhoto1Uri;
	private String mPhoto2Uri;
	private String mPhoto3Uri;

	protected String cartype = "";
	protected String carcid = "";
	protected int carlength = -1;
	protected int carweight = -1;

	private int bxnum = 0;
	private double beMoney = 0;
	private double bxPrice = 0;
	private double bxTotal = 0;
	private double beTotal = 0;
	protected long audioDuration;

	private DatePickerDialog dateDialog;
	private TimePickerDialog timeDialog;
	private boolean isSend;
	private AlertDialog cargoTypeDialog;
	private AlertDialog carRequireDialog;
	private AlertDialog carWeightDialog;
	private AlertDialog carLongDialog;
	private AlertDialog carTypeDialog;

	private AlertDialog payDialog; //1.8

	CropParams mCropParams = new CropParams();
	private int currentSelectImageType;
	protected CarTypeSecond carTypeSecond;

	private DatepickerPopwindow datePop;
	private TimepickerPopwindow timePop;
	private Baoxian baoxian;

	public static final int SELECT_IMAGE1 = 0;
	public static final int SELECT_IMAGE2 = SELECT_IMAGE1 + 1;
	public static final int SELECT_IMAGE3 = SELECT_IMAGE2 + 1;

	private SupplyOrder supplyOrder;
	private String[] supplyImages = new String[3];
	private String imageUrls = "";
	private CascadingMenuPopWindow cascadingMenuPopWindowStart;
    private CascadingMenuPopWindow cascadingMenuPopWindowEnd;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_send_goods);

		initData();
		initView();
		setUpView();
	}

	private void initData() {
		caruserid = getIntent().getStringExtra(ExtraName.caruserid);
		supplyOrder = (SupplyOrder) getIntent().getSerializableExtra(ExtraName.supplyItem);

		isCar = !TextUtils.isEmpty(caruserid);
		manager = new AudioPlayManager(this);
		baoxian = AccountManager.getBaoxian();

		beMoney = Double.parseDouble(baoxian.getBxmoney());
		bxPrice = Double.parseDouble(baoxian.getBxprice());

		if (supplyOrder != null) {
			startPoi = new PoiEntity();
			startPoi.setId(supplyOrder.getOrigincityid());
			try{
				startPoi.setLng(Double.parseDouble(supplyOrder.getOriginlng()));
			}catch(Exception e){
				
			}
			try{
				startPoi.setLat(Double.parseDouble(supplyOrder.getOriginlat()));
			}catch(Exception e){
				
			}
			

			endPoi = new PoiEntity();
			endPoi.setId(supplyOrder.getReceivecityid());
			try{
				endPoi.setLng(Double.parseDouble(supplyOrder.getReceivelng()));
			}catch(Exception e){
				
			}
			try{
				endPoi.setLat(Double.parseDouble(supplyOrder.getReceivelat()));
			}catch(Exception e){
				
			}

			String[] images = supplyOrder.getImages();

			for (int i = 0; i < images.length; i++) {
				if (i > 2) {
					break;
				}
				supplyImages[i] = images[i];
			}
		}
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mContentSv = (ScrollView) this.findViewById(R.id.sv_content);

		mStartAddressLayout = this.findViewById(R.id.layout_shifadi);
		mEndAddressLayout = this.findViewById(R.id.layout_mudidi);
		mStartAddressText = (TextView) this.findViewById(R.id.textview_shifadi);
		mEndAddressText = (TextView) this.findViewById(R.id.textview_mudidi);
		mStartAddressEdit = (EditText) this.findViewById(R.id.edittext_start_address);
		mEndAddressEdit = (EditText) this.findViewById(R.id.edittext_end_address);
		mSendTimeLayout = this.findViewById(R.id.layout_send_time);
		mSendTimeText = (TextView) this.findViewById(R.id.textview_send_time);
		mWantTimeLayout = this.findViewById(R.id.layout_want_arrive_time);
		mWantTimeText = (TextView) this.findViewById(R.id.textview_want_arrive_time);
		mCargoTypeLayou = this.findViewById(R.id.layout_cargo_type);
		mCargoTypeText = (TextView) this.findViewById(R.id.textview_cargo_type);
		mCargoweightLayout = this.findViewById(R.id.layout_cargo_weight);
		mCargoweightEdit = (EditText) this.findViewById(R.id.edittext_cargo_weight);
		mCargoTijiLayout = this.findViewById(R.id.layout_cargo_tiji);
		mCargoTijiText = (EditText) this.findViewById(R.id.textview_cargo_tiji);
		mCargoweight1Layout = this.findViewById(R.id.layout_cargo_weight1);
		mCargoweight1Edit = (EditText) this.findViewById(R.id.edittext_cargo_weight1);
		mCargoTiji1Layout = this.findViewById(R.id.layout_cargo_tiji1);
		mCargoTiji1Text = (EditText) this.findViewById(R.id.textview_cargo_tiji1);
		mCargoLongLayout = this.findViewById(R.id.layout_cargo_long);
		mCargoLongEdit = (EditText) this.findViewById(R.id.textview_cargo_long);

		mCargoNameLayou = this.findViewById(R.id.layout_cargo_name);//1.8
		mCargoNameText = (EditText) this.findViewById(R.id.textview_cargo_name);
		mPayLayout = this.findViewById(R.id.layout_pay);
		mPayText = (TextView) this.findViewById(R.id.textview_pay);

		mPhoto1Layout = this.findViewById(R.id.layout_photo1);
		mPhoto2Layout = this.findViewById(R.id.layout_photo2);
		mPhoto3Layout = this.findViewById(R.id.layout_photo3);
		mPhoto1Image = (ImageView) this.findViewById(R.id.imageview_photo1);
		mPhoto2Image = (ImageView) this.findViewById(R.id.imageview_photo2);
		mPhoto3Image = (ImageView) this.findViewById(R.id.imageview_photo3);
		mContactPhoneEdit = (EditText) this.findViewById(R.id.edittext_contact_phone);
		mCarYaoqiuLayout = this.findViewById(R.id.layout_car_ask_for);
		mCarYaoqiuText = (TextView) this.findViewById(R.id.textview_car_ask_for);

		mBxDeleteButton = (TextView) this.findViewById(R.id.button_jian);
		mBxAddButton = (TextView) this.findViewById(R.id.button_jia);
		mBxCountText = (TextView) this.findViewById(R.id.textview_baoxian_count);
		mBxHintText = (TextView) this.findViewById(R.id.textview_baoxian_hint);
		mBxHintCountText = (TextView) this.findViewById(R.id.textview_baoxian_hint_count);

		mYunfeiLayout = this.findViewById(R.id.layout_yunfeibaojia);
		mYunfeiEdit = (EditText) this.findViewById(R.id.edittext_yunfeibaojia);

		mMarkEdit = (EditText) this.findViewById(R.id.edittext_mark);

		mAddedServiceGv = (MeasureGridView) this.findViewById(R.id.gv_service_list);
		mAudioRecordLayout = this.findViewById(R.id.layout_audio_record);
		mAudioRecordText = (TextView) this.findViewById(R.id.text_audio_record);
		mAudioPlayLayout = this.findViewById(R.id.layout_audio_play);
		mReleaseButton = (Button) this.findViewById(R.id.button_release);

		mCarTypeLayout = this.findViewById(R.id.layout_car_type);
		mCarLongLayout = this.findViewById(R.id.layout_car_long);
		mCarWeightLayout = this.findViewById(R.id.layout_car_weight);
		mCarTypeText = (TextView) this.findViewById(R.id.textview_car_type);
		mCarlongText = (TextView) this.findViewById(R.id.textview_car_long);
		mCarWeightText = (TextView) this.findViewById(R.id.textview_car_weight);

		mCargoTiji1Layout.setVisibility(View.GONE);
		mCargoweight1Layout.setVisibility(View.GONE);
		mCargoTijiLayout.setVisibility(View.GONE);
		mCargoweightLayout.setVisibility(View.GONE);
		mCargoLongLayout.setVisibility(View.GONE);

	}

	private void setUpView() {
		mTopbarView.setCenterText("我要发货");
		mTopbarView.setLeftView(true, true);

		List<AddedService> list = DaoUtils.findAllAddedService();
		AddedServiceListAdapter<AddedService> serviceAdapter = new AddedServiceListAdapter<>(this, list, false);
		mAddedServiceGv.setAdapter(serviceAdapter);

		mAddedServiceGv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				AddedService service = (AddedService) parent.getItemAtPosition(position);
				if (mSelectedServiceList.contains(service)) {
					mSelectedServiceList.remove(service);
					view.setActivated(false);
				} else {
					mSelectedServiceList.add(service);
					view.setActivated(true);
				}

			}
		});

		mBxHintText.setText("说明:保险费" + baoxian.getBxprice() + "元/份,保金" + (Integer.parseInt(baoxian.getBxmoney()) / 10000)
				+ "万元／份");

		// 运费报价
		if (isCar) {
			mYunfeiLayout.setVisibility(View.VISIBLE);
		} else {
			mYunfeiLayout.setVisibility(View.GONE);
		}

		// mCargoweightLayout.setVisibility(View.GONE);
		// mCargoTijiLayout.setVisibility(View.GONE);
		// mCargoLongLayout.setVisibility(View.VISIBLE);

		mAudioRecordLayout.setOnClickListener(this);
		mAudioPlayLayout.setOnClickListener(this);
		mReleaseButton.setOnClickListener(this);
		mStartAddressLayout.setOnClickListener(this);
		mEndAddressLayout.setOnClickListener(this);

		mSendTimeLayout.setOnClickListener(this);
		mWantTimeLayout.setOnClickListener(this);
		mCargoTypeLayou.setOnClickListener(this);
		mPhoto1Layout.setOnClickListener(this);
		mPhoto2Layout.setOnClickListener(this);
		mPhoto3Layout.setOnClickListener(this);
		mCarYaoqiuLayout.setOnClickListener(this);
		mBxDeleteButton.setOnClickListener(this);
		mBxAddButton.setOnClickListener(this);


		mPayLayout.setOnClickListener(this); // 1.8

		mCarTypeLayout.setOnClickListener(this);
		mCarLongLayout.setOnClickListener(this);
		mCarWeightLayout.setOnClickListener(this);
		clickCarRequire();
		mContentSv.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				switch (event.getAction()) {
					case MotionEvent.ACTION_MOVE:
						if (isRecording) {
							return true;
						}
						break;
				}
				return false;
			}
		});

		mAudioRecordLayout.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent event) {

				if (!TextUtils.isEmpty(recordPath)) {
					showWarnDialog();
					return true;
				}

				switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						isRecording = true;
						recordAudio();
						break;
					case MotionEvent.ACTION_OUTSIDE:
					case MotionEvent.ACTION_CANCEL:
					case MotionEvent.ACTION_UP:
						isRecording = false;
						manager.stopRecording();
						break;
				}
				return false;
			}
		});

		mAudioPlayLayout.setVisibility(View.GONE);

		mAudioRecordLayout.setVisibility(View.GONE);
		mAddedServiceGv.setVisibility(View.GONE);

		if (supplyOrder != null) {
			mStartAddressText.setText(supplyOrder.getOrigincityname());
			mStartAddressEdit.setText(supplyOrder.getOriginaddress());
			mEndAddressText.setText(supplyOrder.getReceivecityname());
			mEndAddressEdit.setText(supplyOrder.getReceiveaddress());
			mContactPhoneEdit.setText(supplyOrder.getRecemobile());
			mCargoNameText.setText(supplyOrder.getTitle());

			if (supplyImages != null && supplyImages.length > 0) {
				ImageLoader.getInstance().displayImage(supplyImages[0], mPhoto1Image, ImageLoadUtil.build);
				if (supplyImages.length > 1) {
					ImageLoader.getInstance().displayImage(supplyImages[1], mPhoto2Image, ImageLoadUtil.build);
					if (supplyImages.length > 2) {
						ImageLoader.getInstance().displayImage(supplyImages[2], mPhoto3Image, ImageLoadUtil.build);
					}
				}
			}
		}
	}

	protected void showWarnDialog() {
		if (recordDialog != null && recordDialog.isShowing()) {
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("确定重新录音?");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				FileHelper.deleteFile(recordPath);
				recordPath = "";
				mAudioRecordText.setText("按住说话，描述发货信息");
				mAudioPlayLayout.setVisibility(View.GONE);
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});
		recordDialog = builder.create();
		recordDialog.show();
	}

	private void recordAudio() {
		manager.setRecordingListener(new RecordingListener() {

			@Override
			public void updateRecordingTime(int current, String formatTime, long currentTimeMillis) {
				mAudioRecordText.setText("正在录音(" + formatTime + ")");
			}

			@Override
			public void onRecordingStart(long startTimeMillis) {
			}

			@Override
			public void onRecordingFailed(Object reason) {
				mAudioRecordText.setText(reason + "");
				mAudioPlayLayout.setVisibility(View.GONE);
			}

			@Override
			public void onRecordingComplete(String filePath, long duration, String formatTime) {
				audioDuration = duration;
				mAudioRecordText.setText("录音结束(" + formatTime + ")");
				recordPath = filePath;
				mAudioPlayLayout.setVisibility(View.VISIBLE);
			}

			@Override
			public void onAmplitudesUpdate(int level) {
			}
		});

		manager.startRecording();
	}

	@Override
	public void onClick(View v) {
		DeviceHelper.hideIME(mTopbarView);
		switch (v.getId()) {
		case R.id.layout_audio_play:
			if (!TextUtils.isEmpty(recordPath)) {
				manager.startPlayingVoiceByCache(recordPath);
				mAudioPlayLayout.setEnabled(false);
				manager.setPlayingListener(new PlayingListener() {

					@Override
					public void updateProcess(long pos) {

					}

					@Override
					public void onStopPlaying() {
						mAudioPlayLayout.setEnabled(true);
					}

					@Override
					public void onPlayingFailed(Object e) {
						mAudioPlayLayout.setEnabled(true);
					}

					@Override
					public void onPlayingComplete(MediaPlayer mp) {
						mAudioPlayLayout.setEnabled(true);
					}

					@Override
					public void onLoadingUpdate(MediaPlayer mp, int percent) {

					}

					@Override
					public void onLoadingError(MediaPlayer mp, int what, int extra) {
						mAudioPlayLayout.setEnabled(true);
					}

					@Override
					public void onLoadingComplete(MediaPlayer mp) {

					}
				});
			} else {
				showToast("暂无录音");
			}
			break;
		case R.id.button_release:
			// Intent intent = new Intent(this, SendGoodsConfirmActivity.class);
			// startActivity(intent);
			release();
			break;

			case R.id.layout_pay:
				selectPay();
				break;

		case R.id.layout_shifadi:
			if (cascadingMenuPopWindowStart == null) {
    			//向三级menu添加地区数据
        		cascadingMenuPopWindowStart = new CascadingMenuPopWindow(this, false);
        		cascadingMenuPopWindowStart
    					.setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {
    		        		@Override
    		          		public void getValue(Area city, String fullname) {
    		        			mStartAddressText.setText(fullname);
    		          			startPoi = PoiEntityUtils.convert(city, fullname);
    		          		}
    		        	});
        		cascadingMenuPopWindowStart.showAsDropDown(mStartAddressText, 5, 5);
    		} else if (cascadingMenuPopWindowStart != null
    				&& cascadingMenuPopWindowStart.isShowing()) {
    			cascadingMenuPopWindowStart.dismiss();
    		} else {
    			cascadingMenuPopWindowStart.showAsDropDown(mStartAddressText, 5, 5);
    		}
			break;
		case R.id.layout_mudidi:
			if (cascadingMenuPopWindowEnd == null) {
    			//向三级menu添加地区数据
        		cascadingMenuPopWindowEnd = new CascadingMenuPopWindow(this, false);
        		cascadingMenuPopWindowEnd
    					.setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {
    		        		@Override
    		          		public void getValue(Area city, String fullname) {
    		        			mEndAddressText.setText(fullname);
    		          			endPoi = PoiEntityUtils.convert(city, fullname);
    		          		}
    		        	});
        		cascadingMenuPopWindowEnd.showAsDropDown(mEndAddressText, 5, 5);
    		} else if (cascadingMenuPopWindowEnd != null
    				&& cascadingMenuPopWindowEnd.isShowing()) {
    			cascadingMenuPopWindowEnd.dismiss();
    		} else {
    			cascadingMenuPopWindowEnd.showAsDropDown(mEndAddressText, 5, 5);
    		}
			break;
		case R.id.layout_send_time:
			isSend = true;
			selectDate();
			break;
		case R.id.layout_want_arrive_time:
			isSend = false;
			selectDate();
			break;
		case R.id.layout_cargo_type:
			selectCargoType();
			break;
		case R.id.layout_photo1:
			selectImage(SELECT_IMAGE1);
			break;
		case R.id.layout_photo2:
			selectImage(SELECT_IMAGE2);
			break;
		case R.id.layout_photo3:
			selectImage(SELECT_IMAGE3);
			break;
		case R.id.layout_car_ask_for:
			// selectCarRequire();
			clickCarRequire();
			break;
		case R.id.button_jian:
			if (bxnum <= 0) {
				return;
			}
			if (bxnum > 0) {
				bxnum -= 1;
			}
			if (bxnum == 0) {
				mBxHintCountText.setVisibility(View.GONE);
			}

			bxTotal = bxnum * bxPrice;
			beTotal = bxnum * beMoney;

			mBxCountText.setText(bxnum + "");

			mBxHintCountText.setText("保险费" + bxTotal + "元,保金" + (beTotal / 10000) + "万元");
			break;
		case R.id.button_jia:
			bxnum += 1;
			mBxCountText.setText(bxnum + "");

			bxTotal = bxnum * bxPrice;
			beTotal = bxnum * beMoney;

			mBxHintCountText.setText("保险费" + bxTotal + "元,保金" + (beTotal / 10000) + "万元");
			mBxHintCountText.setVisibility(View.VISIBLE);
			break;
		case R.id.layout_car_type:
			selectCarType();
			break;
		case R.id.layout_car_long:
			selectCarLong();
			break;
		case R.id.layout_car_weight:
			selectCarWeight();
			break;
		}
	}

	private void clickCarRequire() {
		if (mCarTypeLayout.getVisibility() == View.VISIBLE) {
			mCarTypeLayout.setVisibility(View.GONE);
			mCarLongLayout.setVisibility(View.GONE);
			mCarWeightLayout.setVisibility(View.GONE);
		} else {
			mCarTypeLayout.setVisibility(View.VISIBLE);
			mCarLongLayout.setVisibility(View.VISIBLE);
			mCarWeightLayout.setVisibility(View.VISIBLE);
		}
	}

	private void selectCarRequire() {
		if (carRequireDialog != null && carRequireDialog.isShowing()) {
			return;
		}
		if (carRequireDialog == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setItems(CarOption.carRequireItems, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case 0:
						selectCarType();
						break;
					case 1:
						selectCarWeight();
						break;
					case 2:
						selectCarLong();
						break;
					}
				}
			});
			carRequireDialog = builder.create();
			carRequireDialog.setTitle("车辆要求");
		}
		carRequireDialog.show();
	}

	protected void selectCarLong() {
		if (carLongDialog != null && carLongDialog.isShowing()) {
			return;
		}
		if (carLongDialog == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setItems(CarOption.carLongItems, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					carlength = which + 1;
					// setCarRequireText();
					mCarlongText.setText(CarOption.carLongItems[which]);
				}
			});
			carLongDialog = builder.create();
			carLongDialog.setTitle("车长");
		}
		carLongDialog.show();
	}

	// protected void setCarRequireText() {
	// StringBuilder sb = new StringBuilder();
	// if (!TextUtils.isEmpty(cartype) && !TextUtils.isEmpty(carcid)) {
	// sb.append(carTypeSecond.getName());
	// }
	// if (carweight != -1) {
	// sb.append("/" + CarOption.carWeightItems[carweight - 1]);
	// }
	// if (carlength != -1) {
	// sb.append("/" + CarOption.carLongItems[carlength - 1]);
	// }
	// mCarYaoqiuText.setText(sb.toString());
	// }

	protected void selectCarWeight() {
		if (carWeightDialog != null && carWeightDialog.isShowing()) {
			return;
		}
		if (carWeightDialog == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setItems(CarOption.carWeightItems, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					carweight = which + 1;
					// setCarRequireText();
					mCarWeightText.setText(CarOption.carWeightItems[which]);
				}
			});
			carWeightDialog = builder.create();
			carWeightDialog.setTitle("载重");
		}
		carWeightDialog.show();
	}

	protected void selectCarType() {
		if (carTypeDialog != null && carTypeDialog.isShowing()) {
			return;
		}
		if (carTypeDialog == null) {
			List<CarTypeFirst> findAllCartype = DaoUtils.findAllCartype();
			final List<CarTypeSecond> carTypeSeconds = new ArrayList<CarTypeSecond>();
			for (CarTypeFirst carType : findAllCartype) {
				List<CarTypeSecond> findAllCartype2 = DaoUtils.findAllCartype(carType.getTypeid());
				carTypeSeconds.addAll(findAllCartype2);
			}
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			CarTypeSecondListAdapter<CarTypeSecond> adapter = new CarTypeSecondListAdapter<CarTypeSecond>(this, carTypeSeconds,
					false);
			builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					carTypeSecond = carTypeSeconds.get(which);
					cartype = carTypeSecond.getParentId();
					carcid = carTypeSecond.getCid();
					// setCarRequireText();
					mCarTypeText.setText(carTypeSecond.getName());
				}
			});
			carTypeDialog = builder.create();
			carTypeDialog.setTitle("车辆类型");

		}
		carTypeDialog.show();
	}

	private void selectPay() {
		if (payDialog != null && payDialog.isShowing()) {
			return;
		}
		if (payDialog == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setItems(new String[]{"在线支付", "货到付款"}, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
						case 0:
							mPayText.setText("在线支付");
							break;
						case 1:
							mPayText.setText("货到付款");
							break;
					}
				}
			});
			payDialog = builder.create();
			payDialog.setTitle("支付方式");
		}
		payDialog.show();
	}

	private void selectCargoType() {
		if (cargoTypeDialog != null && cargoTypeDialog.isShowing()) {
			return;
		}
		if (cargoTypeDialog == null) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setItems(CarOption.cargoItems1, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					shipptype = which + 2;
					mCargoTypeText.setText(CarOption.cargoItems1[which]);

					switch (which) {
					case 0:
						mCargoTijiLayout.setVisibility(View.GONE);
						mCargoweightLayout.setVisibility(View.GONE);
						mCargoTiji1Layout.setVisibility(View.VISIBLE);
						mCargoweight1Layout.setVisibility(View.VISIBLE);
						mCargoLongLayout.setVisibility(View.VISIBLE);
						break;
					case 1:
						mCargoTiji1Layout.setVisibility(View.GONE);
						mCargoweight1Layout.setVisibility(View.GONE);
						mCargoTijiLayout.setVisibility(View.VISIBLE);
						mCargoweightLayout.setVisibility(View.VISIBLE);
						mCargoLongLayout.setVisibility(View.VISIBLE);
						break;
					// case 2:
					// mCargoweightLayout.setVisibility(View.GONE);
					// mCargoTijiLayout.setVisibility(View.VISIBLE);
					// break;
					}
				}
			});
			cargoTypeDialog = builder.create();
			cargoTypeDialog.setTitle("货物类型");
		}
		cargoTypeDialog.show();
	}

	private void selectDate() {
		if (datePop != null && datePop.isShowing()) {
			return;
		}
		if (datePop == null) {

			datePop = new DatepickerPopwindow(this);
			datePop.setOnSelectDateListener(new OnSelectDateListener() {

				@Override
				public void onSelectDate(String date) {
					if (isSend) {
						// selectTime(year, monthOfYear, dayOfMonth);
						// sendTimeYear = year;
						// sendTimeMonth = monthOfYear;
						// sendTimeDay = dayOfMonth;
						// sendTimeHour = hourOfDay;
						// sendTimeMinute = minute;
						sendDate = date;
						mSendTimeText.setText(sendDate);

					} else {
						// wantTimeYear = year;
						// wantTimeMonth = monthOfYear;
						// wantTimeDay = dayOfMonth;
						wantDate = date;
						mWantTimeText.setText(wantDate);
					}
				}
			});
		}
		datePop.showLocation(mTopbarView);
	}


	public void release() {

		if (startPoi == null) {
			showToast("请选择始发地址");
			return;
		}
		String startDetailAddress = mStartAddressEdit.getText().toString().trim();
		if (TextUtils.isEmpty(startDetailAddress)) {
			showToast("请输入始发详细地址");
			return;
		}
		if (endPoi == null) {
			showToast("请选择目的地");
			return;
		}
		String endDetailAddress = mEndAddressEdit.getText().toString().trim();
		if (TextUtils.isEmpty(endDetailAddress)) {
			showToast("请输入目的地详细地址");
			return;
		}

		if (TextUtils.isEmpty(sendDate)) {
			showToast("请选择发货时间");
			return;
		}

		String ordername = mCargoNameText.getText().toString().trim();
		if (TextUtils.isEmpty(ordername)) {
			showToast("请输入货物名称");
			return;
		}

		String payment = mPayText.getText().toString().trim();
		if (TextUtils.isEmpty(payment)) {
			showToast("请选择支付方式");
			return;
		}

		if(shipptype <=0){
			showToast("请选择货物类型");
			return;
		}
		
		String contactPhone = mContactPhoneEdit.getText().toString().trim();
		if (TextUtils.isEmpty(contactPhone)) {
			showToast("请输入联系人电话");
			return;
		}
		if (!StringHelper.isPhoneNumber(contactPhone)) {
			showToast("请输入合格的联系人电话");
			return;
		}

		String cargoWeight = "";
		String cargoTiji = "";
		String shipplength = "";
		if (shipptype == 2) {
			cargoWeight = mCargoweight1Edit.getText().toString().trim();
			cargoTiji = mCargoTiji1Text.getText().toString().trim();
			shipplength = mCargoLongEdit.getText().toString().trim();
		} else if (shipptype == 3) {
			cargoWeight = mCargoweightEdit.getText().toString().trim();
			cargoTiji = mCargoTijiText.getText().toString().trim();
			shipplength = mCargoLongEdit.getText().toString().trim();
		}

		String mark = mMarkEdit.getText().toString().trim();
		String yunfei = mYunfeiEdit.getText().toString().trim();

		SendGoodsEntity entity = new SendGoodsEntity();
		if (isCar) {
			entity.setMoney(yunfei);
			entity.setCaruserid(caruserid);
		}

		entity.setPayment(payment);
		entity.setOrdername(ordername);

		entity.setOrigincityid(startPoi.getId());
		entity.setOriginaddress(mStartAddressText.getText().toString() + startDetailAddress);
		entity.setOriginlng(startPoi.getLng() + "");
		entity.setOriginlat(startPoi.getLat() + "");
		entity.setOrigintime(sendDate);
		entity.setOrigincontact(AccountManager.getUserInfo().getRealname());
		entity.setOriginphone(contactPhone);
		entity.setReceivecityid(endPoi.getId());
		entity.setReceiveaddress(mEndAddressText.getText().toString() + endDetailAddress);
		entity.setReceivelng(endPoi.getLng() + "");
		entity.setReceivelat(endPoi.getLat() + "");
		entity.setReceivetime(wantDate);
		entity.setCartype(cartype);
		entity.setCarcid(carcid);
		entity.setCarlength(carlength == -1 ? "" : carlength + "");
		entity.setCarweight(carweight == -1 ? "" : carweight + "");
		entity.setShipptype(shipptype == -1 ? "" : shipptype + "");
		if (shipptype == 2) {
			if (TextUtils.isEmpty(cargoWeight)) {
				showToast("请填写货物重量");
				return;
			}
		} else if (shipptype == 3) {
			if (TextUtils.isEmpty(cargoTiji)) {
				showToast("请填写货物体积");
				return;
			}
		}
		entity.setShippweight(cargoWeight);
		entity.setShipparea(cargoTiji);
		entity.setShipplength(TextUtils.isEmpty(shipplength) ? "" : shipplength);
		StringBuilder sb = new StringBuilder();
		for (AddedService service : mSelectedServiceList) {
			sb.append(service.getSid() + ",");
		}
		entity.setAttachs(sb.toString());
		entity.setMark(mark);
		entity.setBxprice(baoxian.getBxprice());
		entity.setBxnum(bxnum + "");

		entity.setVoice("");
		entity.setVoicetime("0");
		entity.setShippimgs("");
		// 平台发货时 关联  电商订单
		if (supplyOrder != null) {
			entity.setBusinessorderid(supplyOrder.getOrderid());
		}

		if (TextUtils.isEmpty(mPhoto1Uri) && TextUtils.isEmpty(mPhoto2Uri) && TextUtils.isEmpty(mPhoto3Uri)
				&& TextUtils.isEmpty(recordPath)) {
			StringBuilder images = new StringBuilder();
			for (String image : supplyImages) {
				if (!TextUtils.isEmpty(image)) {
					images.append(image + ",");
				}
			}
			entity.setShippimgs(images.toString());
			if (isCar) {
				releaseByCar(entity);
			} else {

				release(entity);
			}
		} else {
			uploadFile(entity, mPhoto1Uri, FileType.IMAGE, UPLOAD_PHOTO1);
		}

		// entity.setOriginproid("11");
		// entity.setOrigincityid("010");
		// entity.setOriginaddress("圣诞节卡戴珊看风景的健康法第三方");
		// entity.setOriginlng("39.98985");
		// entity.setOriginlat("116.48031");
		// entity.setOrigintime("2015-08-15 12:15");
		// entity.setOrigincontact("是打发");
		// entity.setOriginphone("13120128328");
		// entity.setReceiveproid("12");
		// entity.setReceivecityid("012");
		// entity.setReceiveaddress("sdfjfksdgkdsjg的观点是高仿的发生过");
		// entity.setReceivelng("39.07");
		// entity.setReceivelat("117.12");
		// entity.setReceivetime("2015-08-19 12:15");
		// entity.setCartype("1");
		// entity.setCarcid("3");
		// entity.setCarlength("1");
		// entity.setCarweight("1");
		// entity.setShipptype("1");
		// entity.setShippimgs("");
		// entity.setShippweight("50");
		// entity.setShipparea("");
		// entity.setAttachs("1,2");
		// entity.setMark("第三方价格的施工的老师放假");
		// entity.setBxprice("34");
		// entity.setBxnum("1");
		// entity.setVoice("");
		// entity.setVoicetime("0");

	}

	private void uploadFile(final SendGoodsEntity releaseInfo, String uri, final String type, final int uploadId) {

		if (TextUtils.isEmpty(uri)) {
			setUrl(uploadId, null, releaseInfo);
			return;
		}

		startLoadingDialog();
		RequestService.getInstance().uploadImage(this, uri, type, UploadImageEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					UploadImageEntity entity = (UploadImageEntity) resultData;
					setUrl(uploadId, entity, releaseInfo);
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(msg);
			}
		});
	}

	protected void setUrl(int uploadId, UploadImageEntity entity, SendGoodsEntity releaseInfo) {
		switch (uploadId) {
		case UPLOAD_PHOTO1:
			if (entity != null) {
				releaseInfo.setShippimgs(entity.getData().getFile() + ",");
			} else if (!TextUtils.isEmpty(supplyImages[0])) {
				releaseInfo.setShippimgs(supplyImages[0] + ",");
			}
			uploadFile(releaseInfo, mPhoto2Uri, FileType.IMAGE, UPLOAD_PHOTO2);
			break;
		case UPLOAD_PHOTO2:
			if (entity != null) {
				String shippimgs = releaseInfo.getShippimgs();
				releaseInfo.setShippimgs(shippimgs + entity.getData().getFile() + ",");
			} else if (!TextUtils.isEmpty(supplyImages[1])) {
				String shippimgs = releaseInfo.getShippimgs();
				releaseInfo.setShippimgs(shippimgs + supplyImages[1] + ",");
			}
			uploadFile(releaseInfo, mPhoto3Uri, FileType.IMAGE, UPLOAD_PHOTO3);
			break;
		case UPLOAD_PHOTO3:
			if (entity != null) {
				String shippimgs = releaseInfo.getShippimgs();
				releaseInfo.setShippimgs(shippimgs + entity.getData().getFile() + ",");
			} else if (!TextUtils.isEmpty(supplyImages[2])) {
				String shippimgs = releaseInfo.getShippimgs();
				releaseInfo.setShippimgs(shippimgs + supplyImages[2] + ",");
			}
			uploadFile(releaseInfo, recordPath, FileType.FILE, UPLOAD_AUDIO);
			break;
		case UPLOAD_AUDIO:
			if (entity != null) {
				releaseInfo.setVoice(entity.getData().getFile());
				releaseInfo.setVoicetime((audioDuration * 1000) + "");
			}
			if (isCar) {
				releaseByCar(releaseInfo);
			} else {
				release(releaseInfo);
			}
			break;
		}
	}

	private void release(SendGoodsEntity entity) {
		startLoadingDialog();

		RequestService.getInstance().sendGoods(this, entity, BaseEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					showToast("发货成功");
					toOrderList();
					finish();
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(msg);
			}
		});
	}

	private void releaseByCar(SendGoodsEntity entity) {
		startLoadingDialog();

		RequestService.getInstance().sendGoodsByCar(this, entity, BaseEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					showToast("下单成功");
					toOrderList();
					finish();
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(msg);
			}
		});
	}

	private void toOrderList() {
		Intent intent = new Intent(this, OrderManagerActivity.class);
		startActivity(intent);
	}

	private void selectImage(int selectType) {

		currentSelectImageType = selectType;

		AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
		builder1.setItems(new String[]{"相机", "相册"}, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
					case 0:
						/*getCropParams().uri = CameraUtil.buildUri(System.currentTimeMillis() + ".jpg");
						CropHelper.clearCachedCropFile(mCropParams.uri);
						// CropHelper.sendCamreaSelectPhoto(SellsGoodsActivity.this);
						Intent intent = CropHelper.buildCaptureIntent(getCropParams().uri);
						startActivityForResult(intent, CropHelper.REQUEST_CAMERA);*/
						CameraUtil.capture(SendGoodsEcActivity.this);
						break;
					case 1:
						/*mCropParams.uri = CameraUtil.buildUri(System.currentTimeMillis() + ".jpg");
						CropHelper.clearCachedCropFile(mCropParams.uri);
						// CropHelper.sendGalleryPhotoForResult(SellsGoodsActivity.this);
//                        CropHelper.clearCachedCropFile(mCropParams.uri);
						startActivityForResult(CropHelper.buildCropFromGalleryIntent(mCropParams), CropHelper.REQUEST_CROP);*/
						CameraUtil.photo(SendGoodsEcActivity.this);
						break;
				}
			}
		});
		builder1.create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		CameraUtil.handleResult(this, requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case SELECT_START_POI:
				startPoi = (PoiEntity) data.getSerializableExtra(ExtraName.poi);
				mStartAddressText.setText(startPoi.getTitle());
				break;
			case SELECT_END_POI:
				endPoi = (PoiEntity) data.getSerializableExtra(ExtraName.poi);
				mEndAddressText.setText(endPoi.getTitle());
				break;
//			case CropHelper.REQUEST_CAMERA:
//				onPhotoCropped(getCropParams().uri);
//				break;
//			case CropHelper.REQUEST_CROP:
//				onPhotoCropped(Uri.parse(CropFileUtils.getSmartFilePath(this, data.getData())));
//				break;
			}
		}
	}

	@Override
	public CropParams getCropParams() {
		return mCropParams;
	}

	@Override
	public void onPhotoCropped(Uri u) {
		String uri = u.getPath();
		Logger.d(Logger.LogTag.UI, "Crop Uri in path: " + uri);
		// Toast.makeText(this, "Photo cropped!", Toast.LENGTH_LONG).show();

		switch (currentSelectImageType) {
		case SELECT_IMAGE1:
			LoadUtils.getInstance().loadImage(mPhoto1Image, "file://" + uri, 0, 5);
			mPhoto1Uri = uri;
			supplyImages[0] = "";
			break;
		case SELECT_IMAGE2:
			LoadUtils.getInstance().loadImage(mPhoto2Image, "file://" + uri, 0, 5);
			mPhoto2Uri = uri;
			supplyImages[1] = "";
			break;
		case SELECT_IMAGE3:
			LoadUtils.getInstance().loadImage(mPhoto3Image, "file://" + uri, 0, 5);
			mPhoto3Uri = uri;
			supplyImages[2] = "";
			break;
		}

		// mFrontIdImage.setImageBitmap(CropHelper.decodeUriAsBitmap(this,
		// mCropParams.uri));
		// uploadInfo();
	}

	@Override
	public void onCropCancel() {
		// Toast.makeText(this, "Crop canceled!", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onCropFailed(String message) {
		Toast.makeText(this, "Crop failed:" + message, Toast.LENGTH_LONG).show();
	}

	@Override
	public Activity getContext() {
		return this;
	}

	@Override
	protected void onDestroy() {
		if (getCropParams() != null)
			CropHelper.clearCachedCropFile(getCropParams().uri);
		if (cascadingMenuPopWindowStart != null) {
			cascadingMenuPopWindowStart.dismiss();
		}
		if (cascadingMenuPopWindowEnd != null) {
			cascadingMenuPopWindowEnd.dismiss();
		}
		
		super.onDestroy();
	}
}
